<script lang="tsx">
/**
 * 图片展示组件
 */
export default {
  name: "yy-image-list"
}
</script>

<script lang="tsx" setup>
import {computed, Ref, ref, watch} from "vue"
import NoData from "../yy-no-data/index.vue"
import {YyImageListCustomerEvents, YyImageListCustomerProps} from "./index.ts"

/**
 * 定义emit
 */
const emit: any = defineEmits<YyImageListCustomerEvents>()

/**
 * 定义props
 */
interface YyImageListProps {
  modelValue: string
  props?: YyImageListCustomerProps
}

const props = withDefaults(defineProps<YyImageListProps>(), {
  props: () => ({
    segment: ",",
    width: 100,
    height: 100,
    zoomRate: 1.2,
    maxScale: 7,
    minScale: 0.2,
    fit: "cover",
    isRem: true
  })
})

/**
 * 图片数据
 */
const imgList: Ref<string[]> = ref([])

/**
 * 初始化数据
 */
const initImgList = (data: string) => {
  if (!data) {
    imgList.value = []
    emit("error")
    return
  }
  const segments = data.split(props.props.segment || ",")
  imgList.value = segments.filter(segment => segment.trim() !== "")
  emit("load")
}

/**
 * 计算样式
 */
const style = computed(() => {
  if (props.props.isRem) {
    return {
      width: props.props.width + "rem",
      height: props.props.height + "rem"
    }
  } else {
    return {
      width: props.props.width + "px",
      height: props.props.height + "px"
    }
  }
})

/**
 * 监视数据变化
 */
watch(
    () => props.modelValue,
    (modelValue) => {
      initImgList(modelValue || "")
    },
    {immediate: true}
)

// 同时监视props的变化，确保组件响应式更新
watch(
    () => props.props,
    () => {
      initImgList(props.modelValue || "")
    },
    {deep: true}
)
</script>

<template>
  <div class="yy-image-list">
    <div v-if="imgList.length > 0" class="list">
      <div
          v-for="(item, index) in imgList"
          :key="index"
          :class="{ 'single-image': imgList.length === 1 }"
          class="item"
      >
        <el-image
            :fit="props.props.fit"
            :initial-index="index"
            :max-scale="props.props.maxScale"
            :min-scale="props.props.minScale"
            :preview-src-list="imgList"
            :src="item"
            :style="style"
            :zoom-rate="props.props.zoomRate"
            append-body
            preview-teleported
            show-progress
        />
      </div>
    </div>
    <div v-else :style="style" class="no-data">
      <no-data/>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.yy-image-list {
  .list {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;

    .item {
      &:not(.single-image) {
        flex: 0 0 auto;
      }
    }
  }

  .no-data {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>